package inferenceEngine.types;

import inferenceEngine.labels.Label;
import inferenceEngine.labels.LabelCollection;

import java.util.ArrayList;
import java.util.List;

import org.dom4j.Element;

/**
 * solver for labels conflict
 * @author Boshi Li
 *
 */
public class ConflictSolver {
	
	private ArrayList<String> conditions = new ArrayList<String>();
	private ArrayList<String> solutions = new ArrayList<String>();
	
	private ArrayList<String> elimited = new ArrayList<String>(); 
	@SuppressWarnings("unchecked")
	public ConflictSolver( Element e ){		
		List<Element> ifs =  e.elements("if") ;
		List<Element> thens =  e.elements("then") ;
		for( Element ele : ifs ){
			String name = ele.attribute("label").getValue();
			conditions.add( name );
		}
		for( Element ele : thens ){
			String name = ele.attribute("label").getValue();
			solutions.add( name );
		}
	}
	
	/**
	 * solve labels' conflict
	 * @param collection
	 */
	public boolean solve( LabelCollection collection ){
		boolean existConflict = true;
		for( String s : conditions ){
			if( !collection.contains(s) ){				
				existConflict = false;				
				break;
			}
		}
		boolean existRecommended = false;
		if( existConflict ){
			for( String s : solutions ){
				int index = collection.getIndex( s );
				Label label = collection.get(index);
				if( label.isRecommended() ){
					elimited.add( s + "[Recommended]" );
					collection.remove(s);
					existRecommended = true;
				}				
			}
			
			if( !existRecommended ){
				for( String s : solutions ){
					elimited.add( s );
					collection.remove(s);
				}
			}
		}
		return existConflict;
	}
	
	public String getLog(){
		StringBuilder sb = new StringBuilder();
		sb.append("if exist ");
		for( int i=0; i<conditions.size(); i++ ) {
			sb.append( "'" + conditions.get(i) + "'"  );
			if( i != conditions.size()-1 ){
				sb.append( " and ");
			}
		}
		sb.append(" then eliminate  ");
		for( int i=0; i<elimited.size(); i++ ) {
			sb.append( "'" + elimited.get(i) + "'" );
			if( i != conditions.size()-1 ){
				sb.append( " and ");
			}
		}
		return sb.toString();
	}
	
}
